package com.idvert.smsplugin;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SMSBroadcastReceiver extends BroadcastReceiver {

    final String TAG = getClass().getSimpleName();

    public static final String SMS_RECEICED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    private MessageListener messageListener;

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d(TAG, "----> SMSBroadcastReceiver onReceive");

        if (intent.getAction().equals(SMS_RECEICED_ACTION)) {
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            for (Object pdu: pdus) {
                SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
                String sender = message.getDisplayOriginatingAddress();

                String content = message.getDisplayMessageBody();
                long date = message.getTimestampMillis();
                Date timeDate = new Date(date);
                @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
                String time = simpleDateFormat.format(timeDate);

                PhoneMessage phoneMessage = new PhoneMessage(sender, content, time);
                messageListener.onReceive(phoneMessage);

                abortBroadcast();
            }
        }
    }

    public interface MessageListener {
        void onReceive(PhoneMessage message);
    }

    public void setMessageListener(MessageListener listener) {
        this.messageListener = listener;
    }
}
